<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="患者姓名" prop="patientName">
        <el-input v-model="queryParams.patientName" placeholder="请输入患者姓名" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="血片编号" prop="sliceNo">
        <el-input v-model="queryParams.sliceNo" placeholder="请输入血片编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="手机号" prop="tel">
        <el-input v-model="queryParams.tel" placeholder="请输入手机号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="采血日期" prop="createTime">
        <el-date-picker clearable v-model="queryParams.createTime" type="date" value-format="yyyy-MM-dd" placeholder="请输入采血日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="筛查项目" prop="screening">
        <el-cascader style="font-size: 14px;"  placeholder="类目搜索：请输入类目名称"
                     :props="defaultParams"
                     :options="options"
                     v-model="queryParams.screening"
                     ref="screeningType"
                     filterable clearable></el-cascader>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

  <el-row :gutter="10" class="mb8" id="btn">
      <el-col :span="1.5">
        <el-button type="primary"  plain icon="el-icon-plus" size="mini" :disabled="multiple" @click="handleChange" >老年综合评估</el-button>
      </el-col>
 <!--       <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="multiple" @click="handleProcess" v-hasPermi="['his:patient:process']">不合格血片标记</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-upload2" size="mini" @click="handleImport1" v-hasPermi="['his:attribute:batch']">批量上传指标</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-upload2" size="mini" @click="handleImport2" v-hasPermi="['his:attribute:mda']" >批量上传丙二醛</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-edit" size="mini" :disabled="multiple" @click="handleCalculation" v-hasPermi="['his:attribute:calculate']">计算结果</el-button>
      </el-col>-->
    </el-row>

    <el-table v-loading="loading" :data="patientList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="序号" align="center" prop="hisPatientList[0].id" width="50px"/>
      <el-table-column label="姓名" align="center" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <router-link :to="'/his/reg_treat/patient_reg/' + scope.row.hisPatientList[0].id" class="link-type">
            <el-tooltip class="item" effect="light" content="随访登记卡" placement="right">
            <span>{{ scope.row.hisPatientList[0].patientName }}</span>
            </el-tooltip>
          </router-link>
        </template>
        <router-view :key="$route.fullPath" />
      </el-table-column>
      <el-table-column label="性别" align="center" prop="gender" width="50px">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.his_doctor_sex" :value="scope.row.hisPatientList[0].gender" />
        </template>
      </el-table-column>
      <el-table-column label="ID血片编号" align="center" prop="hisPatientList[0].sliceNo" width="129px"/>
      <el-table-column label="电话" align="center" prop="hisPatientList[0].tel" width="109px"/>
      <el-table-column label="采血单位" align="center" prop="hisPatientList[0].sysDept.deptName" width="179px"/>
      <el-table-column label="筛查项目" align="center" prop="hisPatientList[0].subscreening" width="239px"/>
      <el-table-column label="年龄" align="center" prop="hisPatientList[0].age" width="50px"/>
      <el-table-column label="体重" align="center" prop="hisPatientList[0].weight" />
      <el-table-column label="采血日期" align="center" prop="hisPatientList[0].ctime" width="132px">
      <template slot-scope="scope">
        <span>{{ parseTime(scope.row.hisPatientList[0].ctime, '{y}-{m}-{d} {h}:{i}') }}</span>
      </template>
      </el-table-column>
      <el-table-column label="计算模型" align="center" prop="hisPatientList[0].formula" width="80px"/>
      <el-table-column label="筛查结果" align="center" prop="hisPatientList[0].status" width="96px">
        <template slot-scope="scope">
<!--          {{scope.row.hisPatientList[0].status}}-->
          <el-tag size="mini" v-if="(scope.row.hisPatientList[0].status+'').indexOf('1')!=-1" type="warning">已随访</el-tag>
          <el-tag size="mini" v-if="(scope.row.hisPatientList[0].status+'').indexOf('2')!=-1" type="success">已干预</el-tag>
          <el-tag size="mini" v-if="(scope.row.hisPatientList[0].status+'').indexOf('3')!=-1" type="info">已退回</el-tag>
          <el-tag size="mini" v-if="(scope.row.hisPatientList[0].status+'').indexOf('4')!=-1" type="danger">已召回</el-tag>
        </template>
      </el-table-column>

      <el-table-column type="expand" label="">
        <template slot-scope="props">
          <el-form label-position="left" class="table-expand">
            <el-form-item label="">
              <span style="margin-right: 32px; font-weight: bolder; color: #ddaf38" v-if="props.row.hisPatientList[0].screeningList[0]!=null">{{props.row.hisPatientList[0].screeningList[0].screeningItem.replace("老年衰弱","衰弱症")}}</span>
              <span style="margin-right: 32px" v-if="props.row.hisPatientList[0].screeningList[0]!=null">{{props.row.hisPatientList[0].screeningList[0].referenceRange}}</span>
              <span style="margin-right: 32px" v-if="props.row.hisPatientList[0].screeningList[0]!=null">{{props.row.hisPatientList[0].screeningList[0].screeningResult}}</span>
              <span style="margin-right: 32px" v-if="props.row.hisPatientList[0].screeningList[0]!=null">{{props.row.hisPatientList[0].screeningList[0].riskWarning}}</span>
            </el-form-item>
            <el-form-item label="">
              <span style="margin-right: 32px; font-weight: bolder; color: #ddaf38" v-if="props.row.hisPatientList[0].screeningList[1]!=null">{{props.row.hisPatientList[0].screeningList[1].screeningItem.replace("老年衰弱","衰弱症")}}</span>
              <span style="margin-right: 32px" v-if="props.row.hisPatientList[0].screeningList[1]!=null">{{props.row.hisPatientList[0].screeningList[1].referenceRange}}</span>
              <span style="margin-right: 32px" v-if="props.row.hisPatientList[0].screeningList[1]!=null">{{props.row.hisPatientList[0].screeningList[1].screeningResult}}</span>
              <span style="margin-right: 32px" v-if="props.row.hisPatientList[0].screeningList[1]!=null">{{props.row.hisPatientList[0].screeningList[1].riskWarning}}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>

      <el-table-column label="录入时间" align="center" prop="createTime" width="152px">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.hisPatientList[0].createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width"width="129px" >
        <template slot-scope="scope">
          <router-link :to="'/his/reg_treat/patient_edit/' + scope.row.hisPatientList[0].id">
            <el-button type="text" icon="el-icon-edit">查看</el-button>
          </router-link>

          <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row.hisPatientList[0])">
            <span class="el-dropdown-link">
              <i class="el-icon-d-arrow-right el-icon--right"></i>更多
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="handleSf" icon="el-icon-circle-check">随访登记</el-dropdown-item>
              <el-dropdown-item command="handleGy" icon="el-icon-user">筛查干预</el-dropdown-item>
              <el-dropdown-item command="handleTh" icon="el-icon-s-release">血斑退回</el-dropdown-item>
              <el-dropdown-item command="handleZh" icon="el-icon-s-opportunity">血斑召回</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>

        </template>
      </el-table-column>

    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                @pagination="getList" />

    <!-- 添加或修改患者对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="560px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="96px">
        <el-form-item label="患者姓名" prop="patientName">
          <el-input v-model="form.patientName" placeholder="请输入患者姓名" />
        </el-form-item>
        <el-form-item label="所属机构" prop="unit">
          <el-input v-model="form.unit" placeholder="请输入所属机构ID" disabled/>
        </el-form-item>
        <el-form-item label="患者电话" prop="tel">
          <el-input v-model="form.tel" placeholder="请输入患者电话" />
        </el-form-item>
        <el-form-item label="血片编号" prop="sliceNo">
          <el-input v-model="form.sliceNo" placeholder="请输入血片编号" />
        </el-form-item>
        <el-form-item label="身份证号" prop="idCard">
          <el-input v-model="form.idCard" placeholder="请输入身份证号" />
        </el-form-item>
        <el-form-item label="患者年龄" prop="age">
          <el-input v-model="form.age" placeholder="请输入患者年龄" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <!--          <el-input v-model="form.gender" placeholder="请输入性别" />-->
          <el-select v-model="form.gender" placeholder="请选择性别" clearable>
            <el-option
              v-for="dict in dict.type.his_doctor_sex"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>

        </el-form-item>
        <el-form-item label="地址信息" prop="address">
          <el-input v-model="form.address" placeholder="请输入地址信息" />
        </el-form-item>
        <el-form-item label="出生日期" prop="patientDate">
          <el-date-picker clearable
                          v-model="form.patientDate"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择出生日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="过敏史" prop="allergy">
          <el-input v-model="form.allergy" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <!--        <el-form-item label="删除标志" prop="delFlag">
                  <el-input v-model="form.delFlag" placeholder="请输入删除标志" />
                </el-form-item>-->
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 审核对话框 -->
    <el-dialog :title="title" :visible.sync="process" width="390px" append-to-body>
      <el-form ref="formProcess" :model="formProcess" :rules="rulesProcess" label-width="96px">
        <el-form-item label="审核状态" prop="status">
          <el-select v-model="formProcess.status" placeholder="请选择审核状态" clearable>
            <el-option
              v-for="dict in selectOptions.status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
              :disabled="dict.disabled"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitProcess">确 定</el-button>
        <el-button @click="handleCancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 计算模型对话框 -->
    <el-dialog :title="title" :visible.sync="calculation" width="390px" append-to-body>
      <el-form ref="formCalculation" :model="formCalculation" :rules="rulesFormula" label-width="96px">
        <el-form-item label="计算模型" prop="formula">
          <el-select v-model="formCalculation.formula" placeholder="请选择计算模型"  clearable>
            <el-option
              v-for="dict in selectOptions.riskType"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
              :disabled="dict.disabled"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitCalculation" :disabled="fdisabled" >确 定</el-button>
        <el-button @click="handleCancel">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 导入对话框1 -->
    <el-dialog :title="upload1.title" :visible.sync="upload1.open" width="400px" append-to-body>
      <el-upload
        ref="upload1"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload1.headers"
        :action="upload1.url + '?updateSupport=' + upload1.updateSupport + '&patientId=' + upload1.patientId+ '&formula=' + upload1.formula"
        :disabled="upload1.isUploading"
        :on-progress="handleFileUploadProgress1"
        :on-success="handleFileSuccess1"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">

          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload1.updateSupport" disabled/> 是否更新已经存在的用户数据
            <el-input v-model="upload1.patientId" type="hidden" ></el-input>
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm1">确 定</el-button>
        <el-button @click="upload1.open = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 导入对话框2 -->
    <el-dialog :title="upload2.title" :visible.sync="upload2.open" width="400px" append-to-body>
      <el-upload
        ref="upload2"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload2.headers"
        :action="upload2.url + '?updateSupport=' + upload2.updateSupport + '&patientId=' + upload2.patientId+ '&formula=' + upload2.formula"
        :disabled="upload2.isUploading"
        :on-progress="handleFileUploadProgress2"
        :on-success="handleFileSuccess2"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">

          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload2.updateSupport" checked disabled/> 是否更新已经存在的用户数据
            <el-input v-model="upload2.patientId" type="hidden" ></el-input>
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm2">确 定</el-button>
        <el-button @click="upload2.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>

</template>
<style>

.table-expand {
  font-size: 0;
}
.table-expand label {
  width: 100px;
  color: #ddaf38;
}
.table-expand .el-form-item {
  margin-left: 824px;
  margin-bottom: 0;
}

 #btn .el-button--info.is-plain{
   color: #719df5;
   background: #f2f2fd;
   border-color: #d3d4d6;
 }
#btn .el-button--info.is-plain:hover, .el-button--info.is-plain:focus {
  background: #909399;
  border-color: #909399;
  color: #FFFFFF;
}
</style>

<script>
import {register, updatePatient, updateProcess, addPatient, updateBpn, listJszRisk } from '@/api/his/mda'
import {changeLnpg} from '@/api/his/screening'
import { calculationProcess } from '@/api/his/attribute'
import { getToken } from '@/utils/auth'
import { getUserProfile } from '@/api/system/user'
import { getDicts } from '@/api/system/dict/data'

export default {
  dicts: [
    'his_doctor_sex',
    'his_screening_status',
    'his_screening_calculate',
    'his_risk_type',
    'his_saas_type',
    'his_screening_unit',
    'his_bpn_status'
  ],
  name: "Patient_Risk",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 患者表格数据
      patientList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      process: false,
      calculation: false,
      fdisabled:false,
      // 查询参数
      queryParams: {
        delFlag: 0,
        screeningType:'老年衰弱/肌少症',
        subscreening:'实验室老年衰弱/肌少症',
        pageNum: 1,
        pageSize: 10,
        patientName: null,
        screening:null,
        tel: null,
        idCard: null,
        age: null,
        gender: null,
        address: null,
        patientDate: null,
        createTime: null
      },
      screeningOptions:[
        {lable:'实验室老年衰弱/肌少症',value:'实验室老年衰弱/肌少症'},
        {lable:'快速综合评估',value:'快速综合评估'},
      ],
      options: [
        {levelName:'肌少症',typeId:'肌少症',typeList:[/* {typeId:'低风险',levelName:'低风险'}, */{typeId:'中风险',levelName:'中风险'},{typeId:'高风险',levelName:'高风险'}]},
        {levelName:'老年衰弱',typeId:'老年衰弱',typeList:[/* {typeId:'低风险',levelName:'低风险'}, */{typeId:'中风险',levelName:'中风险'},{typeId:'高风险',levelName:'高风险'}]}
      ],
      beforeMerchantId: '',
      defaultParams: {
        label: 'levelName',
        value: 'typeId',
        children: 'typeList'
      },
      selectOptions:{
        status:[],
        riskType:[]
      },
      // 表单参数
      form: {},
      formProcess:{
        ids:[],
        status:""
      },
      formCalculation:{
        ids:[],
        formula:""
      },
      formBpn:{
        bpns:[],
        status:""
      },
      bpns:[],
      // 表单校验
      rules: {
        patientName: [
          { required: true, message: "姓名不能为空", trigger: "blur" }
        ],
        tel: [
          { required: true, message: "电话不能为空", trigger: "blur" }
        ],
        sliceNo: [
          { required: true, message: "血片编号不能为空", trigger: "blur" }
        ],
        idCard: [
          { required: true, message: "身份证号不能为空", trigger: "blur" }
        ],
      },
      rulesProcess:{
        status: [
          { required: true, message: "请选择审核状态", trigger: "change" }
        ],
      },
      rulesFormula:{
        formula: [
          { required: true, message: "请选择计算模型", trigger: "change" }
        ],
      },

      // 导入指标参数
      upload1: {
        patientId: 0,
        // 是否显示弹出层（数据导入）
        open: false,
        // 弹出层标题（数据导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/his/attribute/batchImportData",
        formula:0, //默认0 用于参数导入，不计算
      },
      upload2: {
        patientId: 0,
        // 是否显示弹出层（数据导入）
        open: false,
        // 弹出层标题（数据导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/his/attribute/batchMdaImportData",
        formula:0, //默认0 用于参数导入，不计算
      }
    };
  },
  watch: {
    '$route': function () {
      this.getList()
    }
  },
  created() {
    this.getList();
    this.getDicts();
    //this.getUser();
  },
  methods: {
    // 更多操作触发
    handleCommand(command, row) {
      const patientId = row.id;
      switch (command) {
        case "handleSf":
          this.$router.push("/his/reg_treat/patient_reg/" + patientId);
          break;
        case "handleGy":
          this.$router.push("/his/reg_treat/patient_gy/" + patientId);
          break;
        case "handleZh":
          this.$router.push("/his/reg_treat/patient_zh/" + patientId);
          break;
        case "handleTh":
          this.$router.push("/his/reg_treat/patient_th/" + patientId);
          break;
        default:
          break;
      }
    },

    // 生成表头序号
    indexMethod(index) {
      this.queryParams.pageNum <= 0 ? this.queryParams.pageNum = 1 : this.queryParams.pageNum
      if(this.queryParams.pageNum != 1) {

        return index + 1 + ((this.queryParams.pageNum - 1) * this.queryParams.pageSize)
      }
      // 否则直接返回索引+1作为序号
      return index + 1
    },
    getFormula(rows){
      if(rows==3){
        this.fdisabled = true;
        this.$modal.alert('风险计算模型三暂不支持计算')
      }else{
        this.fdisabled = false;
      }
    },
    getDicts(){
      getDicts("his_screening_status").then(response => {
        response.data.forEach((self,index) => {
          var disabled = false;
          if(self.dictLabel === '血片不合格'){
            this.selectOptions.status.push({ value: self.dictValue, label: self.dictLabel,disabled: disabled })
          }
        });
      });
      getDicts("his_screening_calculate").then(response => {
        response.data.forEach((self,index) => {
          var disabled = false;
          if(self.dictLabel === '计算模型三'){
            disabled = true;
          }
          this.selectOptions.riskType.push({ value: self.dictValue, label: self.dictLabel,disabled: disabled })
        });
      });
    },
    /** 查询患者列表 */
    getList() {
      this.loading = true;
      listJszRisk(this.queryParams).then(response => {
        //console.log('this.queryParams: '+JSON.stringify(this.queryParams))
        console.log('response==>',JSON.stringify(response))
        this.patientList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = this.process = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        patientId: null,
        patientName: null,
        tel: null,
        idCard: null,
        age: null,
        gender: null,
        address: null,
        patientDate: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        unit: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      if(this.queryParams.screening!=null){
        this.queryParams.screeningItem = this.queryParams.screening[0];
        this.queryParams.riskWarning = this.queryParams.screening[1];
      }
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getUser();
      this.open = true;
      this.title = "添加患者";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      //alert(row.patientId)
      this.$router.push({ path: '/his/reg_treat/patient_edit', query: { id: row.patientId }})

      /* const patientId = row.patientId || this.ids
      getPatient(patientId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改患者";
      }); */
    },

    /** 计算按钮操作 */
    handleCalculation(row){
      const id = row.id || this.ids
      this.calculation = true;
      this.title = "计算结果";
      this.formCalculation.ids = id;
    },
    submitCalculation() {
      //console.log('this.form',JSON.stringify(this.form))
      this.$refs["formCalculation"].validate(valid => {
        if (valid) {
          this.$modal.confirm('是否确认计算ID为"' + this.formCalculation.ids + '"的数据项？').then(() => {
            const ids = [];//this.formProcess.ids;
            this.formCalculation.ids.forEach((self)=>{
              ids.push(self+'-'+this.formCalculation.formula)
            })
            return calculationProcess(ids);
          }).then((result)=>{
            //console.log('res',result)
            this.getList();
            this.calculation = false;

            //this.$alert(result.msg.replace("导入","计算").replace("导入","计算"), "计算结果", { dangerouslyUseHTMLString: true });

            if(result.msg.search('导入成功0条')!=-1){
              this.$modal.msgWarning(result.msg.replace("导入","计算").replace("导入","计算"));
            }else{
              this.$modal.msgSuccess(result.msg.replace("导入","计算").replace("导入","计算"));
            }
          }).catch(() => {
            this.calculation = false;
          });
        }
      })
    },

    /** 审核按钮操作 */
    handleProcess(row) {
      //this.reset();
      const id = row.id || this.ids
      this.process = true;
      this.title = "血片标记";
      this.formProcess.ids = id;

      this.formBpn.bpns = this.bpns
    },
    submitProcess() {
      this.$refs["formProcess"].validate(valid => {
        if (valid) {
          const ids = [];//this.formProcess.ids;
          const bpns = [];
          this.formProcess.ids.forEach((self)=>{
            ids.push(self+'-'+this.formProcess.status)
          })
          var state = false;
          this.formBpn.bpns.forEach((self)=>{
            var arr = self.split('-');
            if(arr.length>0 && arr[1]!=0){
              state = true; //有已录数据项
            }
            const status = this.formProcess.status==5?2:1;
            bpns.push(arr[0]+'-'+status)
          })
          if(state){
            this.$modal.msgWarning("选择项中存在已录结果，无法设置血片不合格");
            return;
          }

          this.$modal.confirm('是否确认审核ID为"' + this.formProcess.ids + '"的数据项？').then(() => {
            return updateProcess(ids);
          }).then(()=>{
            updateBpn(bpns);
            this.getList();
            this.$modal.msgSuccess("操作成功");
            this.process = false;
          }).catch(() => {
            this.process = false;
          });
        }
      })
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.hisPatientList[0].id+'@'+item.hisPatientList[0].createTime)
      this.showIds =  selection.map(item => item.hisPatientList[0].id) //提示用
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.patientId != null) {
            updatePatient(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            const user = {username:this.form.patientName,nickname:this.form.patientName,password:123456}
            register(user).then(response=>{
              if(response.data.status==0){
                this.form.userId = response.data.id;
                this.form.screeningType = '老年衰弱/肌少症';
                this.form.subscreening = '实验室老年衰弱/肌少症';
                this.form.status = 0;
                addPatient(this.form).then(response => {
                  this.$modal.msgSuccess("新增成功");
                  this.open = false;
                  this.getList();
                });
              }
            });
          }
        }
      });
    },

    /** 按钮操作 */
    handleChange(row) {
      const ids = row.id || this.ids;
      const showIds = row.showIds || this.showIds;
      this.$modal.confirm('是否将编号为"' + showIds + '"的数据项转至老年综合评估？').then(function() {
        return changeLnpg(ids);
      }).then((response) => {
        this.$modal.msgSuccess(response.msg!=null||''?response.msg+response.data+' 条':'操作成功'+response.data+' 条');
      }).catch(() => {});
    },

    handleCancel: function() {
      this.process = false;
      this.calculation = false;
      this.$router.push({ path: '/patient'})
    },


    /** 导入按钮操作 */
    handleImport1() {
      this.upload1.title = "筛查结果导入";
      this.upload1.open = true;
    },
    handleImport2() {
      this.upload2.title = "筛查结果导入（丙二醛）";
      this.upload2.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('his/attribute/importTemplate', {
      }, `attribute_template_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress1(event, file, fileList) {
      this.upload1.isUploading = true;
    },
    handleFileUploadProgress2(event, file, fileList) {
      this.upload2.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess1(response, file, fileList) {
      this.upload1.open = false;
      this.upload1.isUploading = false;
      this.$refs.upload1.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    handleFileSuccess2(response, file, fileList) {
      this.upload2.open = false;
      this.upload2.isUploading = false;
      this.$refs.upload2.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm1() {
      this.$refs.upload1.submit();
    },
    submitFileForm2() {
      this.$refs.upload2.submit();
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download('his/patient/export', {
        ...this.queryParams
      }, `patient_${new Date().getTime()}.xlsx`)
    },

    getUser() {
      getUserProfile().then(response => {
        //console.log('response.data:',response.data)
        this.form.unit = response.data.dept.deptName;
        this.form.deptId = response.data.dept.deptId;
      });
    }
  }
};
</script>
